package binance.model

import java.text.*

class Sell {
    Double price
    Long count
    Buy buy

    static belongsTo = Buy


    static Integer sumInvested(user) {
        def result = 0
        Sell.getAllSells(user).each {
            result += it.buy.price*it.count
        }
        return result
    }

    static Integer sumSale(user) {
        def result = 0
        Sell.getAllSells(user).each {
            result += it.price*it.count
        }
        return result
    }

    static Integer sumProfit(user) {
        def result = 0
        return sumSale(user)-sumInvested(user)
    }

    static Integer avgProfitProc(user) {
        def invested = sumInvested(user);
        if (invested == 0) {
            return 0;
        }
        return (sumSale(user)/invested-1)*100
    }

    String toString(){
        return count +"*"+ price;
    }

    String profit() {
        def rounded = count*(price-buy.price)
        DecimalFormat df = new DecimalFormat("0.00");
        rounded = df.format(rounded);
        return rounded
    }

    String profitProc() {
        def rounded = (price)/(buy.price)
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(rounded)
    }

    String value() {
        def rounded = price*count
        DecimalFormat df = new DecimalFormat("0.00");
        rounded = df.format(rounded);
        return rounded
    }

    String invested() {
        def rounded = buy.price*count
        DecimalFormat df = new DecimalFormat("0.00");
        rounded = df.format(rounded);
        return rounded
    }

    static def getAllSells(user) {
        def buys = Buy.findAllByUser(user)
        def sells = new ArrayList()
        buys.each {
            it.sells.each {
                sells.add(it)
            }
        }
        return sells
    }
}
